import { getToken } from '@/utils/cookie'
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/oj/login',
    },
    {
      path: '/oj/login',
      name: 'login',
      component: () => import('@/views/Login.vue'),
    },
    {
      path: '/oj/layout',
      name: 'layout',
      component: () => import('@/views/Layout.vue'),
      redirect: '/oj/layout/cuser',
      children: [
        {
          path: 'exam',
          name: 'exam',
          component: () => import('@/views/Exam.vue'),
        },
        {
          path: 'examUpdate',
          name: 'examUpdate',
          component: () => import('@/views/ExamUpdate.vue'),
        },
        {
          path: 'question',
          name: 'question',
          component: () => import('@/views/Question.vue'),
        },
        {
          path: 'cuser',
          name: 'cuser',
          component: () => import('@/views/Cuser.vue'),
        },
        {
          path: 'cuserGroup',
          name: 'cuserGroup',
          component: () => import('@/views/CuserGroup.vue'),
        },
        {
          path: 'cuserGroupUpdate',
          name: 'cuserGroupUpdate',
          component: () => import('@/views/CuserGroupUpdate.vue'),
        }
      ]
    },
  ],
})

router.beforeEach((to, from, next) => {
  const token = getToken()
  if (to.path === '/oj/login') {
    if (token) {
      next('/oj/layout')
    } else {
      next()
    }
  } else {
    // 不在白名单中
    if (token) {
      next()
    } else { // 没有登录
      next(`/oj/login?path=${to.path}`)
    }
  }
})

export default router
